package servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import model.Bill;
import model.Department;
import model.Revenue;
import model.Supplier;
import service.ServiceDAOFactory;

@WebServlet("/SystemConfig")
public class SystemConfig extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final String GET_ALL_DEPARTMENT_NAME = "0";
	private static final String ADD_INCOME = "1";
	private static final String ADD_DEPARTMRNT = "2";
	private static final String UPDATEDEPARTMENT = "3";
	private static final String UPDATEINCOME = "4";
	private static final String ADD_SUPPLIER = "5";
	private static final String UPDATE_SUPPLIER = "6";
	private static final String GET_ALL_VENDOR_NAME = "7";
	private static final String ADD_SUPPLIER_ON_BILL = "8";
	private static final String PAY_THE_BILL = "9";
	private static final String ADD_BILL = "10";
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("method");
		String json = "";
		if(method != null){
			switch(method){
			case GET_ALL_DEPARTMENT_NAME:
				json = initDepartment();
				break;
			case ADD_INCOME:
				try {
					json = addIncome(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case ADD_DEPARTMRNT:
				try {
					json = addDepartment(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case UPDATEDEPARTMENT:
				try {
					json = updateDepartment(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case UPDATEINCOME:
				try {
					json = updateIncome(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case ADD_SUPPLIER:
				try {
					json = addSupplier(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case UPDATE_SUPPLIER:
				try {
					json = updateSupplier(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case GET_ALL_VENDOR_NAME:
				json = getVendorName();
				break;
			case ADD_SUPPLIER_ON_BILL:
				try {
					json = addSupplier2(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case PAY_THE_BILL:
				try {
					json = payBill(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			case ADD_BILL:
				try {
					json = addBill(request,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
				break;
			}
		}
		response.getWriter().write(json);
	}
	

	private String addBill(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, Exception {
//		String departmentId = request.getParameter("departmentId");
//		String businessDate = request.getParameter("businessDate");
//		String lastString = request.getParameter("lastString");
//		String text1String = request.getParameter("text1String");
//		String departmentName = ServiceDAOFactory.getRevenueService().findDeptNameById(Integer.parseInt(departmentId));
//		SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
//		Date date = df.parse(businessDate);
//		Date date1 = df.parse(lastString);
//		Revenue revenue = new Revenue(departmentName, date, date1, Integer.parseInt(text1String));
//		boolean flag = ServiceDAOFactory.getRevenueService().saveIncome(revenue);
//		if(flag){
//			return "true";
//		}
//		return "false";
		String vendorId = request.getParameter("vendorId");
		String billDate = request.getParameter("billDate");
		String billDueDate = request.getParameter("billDueDate");
		String total = request.getParameter("total");
		String vendorName = ServiceDAOFactory.getSupplierService().findNameById(Integer.parseInt(vendorId));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse(billDate);
		Date date1 = df.parse(billDueDate);
		Bill bill = new Bill(vendorName,date,date1,Integer.parseInt(total));
		boolean flag = ServiceDAOFactory.getBillService().saveBill(bill);
		if(flag){
			return "true";
		}
		return "false";
	}

	private String payBill(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String billId = request.getParameter("billId");
		String whetherToPay = "T";
		String falg = request.getParameter("falg");
		if(falg.equals("1")){
			String cash = "cash";
			String content = request.getParameter("content");
			Bill bill = new Bill(Integer.parseInt(billId),whetherToPay,cash,content);
			boolean a = ServiceDAOFactory.getBillService().updateBill(bill);
			if(a){
				return "true";
			}
			return "false";
		}else if(falg.equals("0")){
			String check = "check";
			String content = request.getParameter("content");
			if(content != null && content != ""){
				Bill bill = new Bill(Integer.parseInt(billId),whetherToPay,check,content);
				boolean a = ServiceDAOFactory.getBillService().updateBill(bill);
				if(a){
					return "true";
				}
				return "false";
			}
		}
		return null;
	}

	private String addSupplier2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String vendor = request.getParameter("vendor");
		String vendorAddress = request.getParameter("vendorAddress");
		String vendorPhone = request.getParameter("vendorPhone");
		String vendorFax = request.getParameter("vendorFax");
		String contactPerson = request.getParameter("contactPerson");
		Supplier supplier = new Supplier(vendor,vendorAddress,vendorPhone,vendorFax,contactPerson); 
		boolean flag6 = ServiceDAOFactory.getSupplierService().saveSupplier(supplier);
		if(flag6){
			return "true";
		}
		return "false";
	}

	private String getVendorName() {
		try{
			List<Supplier> list = ServiceDAOFactory.getSupplierService().findByName();
			if(list != null){
				com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
				for(Supplier supp :list){
					com.alibaba.fastjson.JSONObject json1 = (com.alibaba.fastjson.JSONObject) JSON.toJSON(supp);
					array.add(json1);
				}
				return array.toString();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return "false";
	}

	private String updateSupplier(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String supplierId = request.getParameter("supplierId");
		String vendor = request.getParameter("vendor");
		String vendorAddress = request.getParameter("vendorAddress");
		String vendorPhone = request.getParameter("vendorPhone");
		String vendorFax = request.getParameter("vendorFax");
		String contactPerson = request.getParameter("contactPerson");
		Supplier supplier = new Supplier(Integer.parseInt(supplierId),vendor,vendorAddress,vendorPhone,vendorFax,contactPerson);
		boolean flag5 = ServiceDAOFactory.getSupplierService().updateSupplier(supplier);
		if(flag5){
			return "true";
		}
		return "false";
	}

	private String addSupplier(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String vendor = request.getParameter("vendor");
		String vendorAddress = request.getParameter("vendorAddress");
		String vendorPhone = request.getParameter("vendorPhone");
		String vendorFax = request.getParameter("vendorFax");
		String contactPerson = request.getParameter("contactPerson");
		Supplier supplier = new Supplier(vendor,vendorAddress,vendorPhone,vendorFax,contactPerson); 
		boolean flag4 = ServiceDAOFactory.getSupplierService().saveSupplier(supplier);
		if(flag4){
			return "true";
		}
		return "false";
	}

	private String updateIncome(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String incomeId = request.getParameter("incomeId");
		String departmentName = request.getParameter("departmentName");
		String lastString = request.getParameter("lastString");
		String text1String = request.getParameter("text1String");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse(lastString);
		Revenue revenue = new Revenue(Integer.parseInt(incomeId), departmentName, date, Double.valueOf(text1String));
		boolean flag3 = ServiceDAOFactory.getRevenueService().updateIncome(revenue);
		if(flag3){
			return "true";
		}
		return "false";
	}

	private String updateDepartment(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String departmentId = request.getParameter("departmentId");
		String departmentName = request.getParameter("departmentName");
		String description = request.getParameter("description");
		boolean flag2 = ServiceDAOFactory.getDepartmentService().updateDepartment(Integer.parseInt(departmentId),departmentName,description);
		if(flag2){
			return "true";
		}
		return "false";
	}

	private String addDepartment(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String departmentName = request.getParameter("departmentName");
		String description = request.getParameter("description");
		boolean flag1 = ServiceDAOFactory.getDepartmentService().saveDepartment(departmentName,description);
		if(flag1){
			return "true";
		}
		return "false";
	}

	private String addIncome(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, Exception {
		String departmentId = request.getParameter("departmentId");
		String businessDate = request.getParameter("businessDate");
		String lastString = request.getParameter("lastString");
		String text1String = request.getParameter("text1String");
		String departmentName = ServiceDAOFactory.getRevenueService().findDeptNameById(Integer.parseInt(departmentId));
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse(businessDate);
		Date date1 = df.parse(lastString);
//		Double.valueOf(d);
//		Double.parseDouble(s);
		Revenue revenue = new Revenue(departmentName, date, date1, Double.valueOf(text1String));
		boolean flag = ServiceDAOFactory.getRevenueService().saveIncome(revenue);
		if(flag){
			return "true";
		}
		return "false";
	}

	private String initDepartment() {
		try{
			List<Department> list = ServiceDAOFactory.getDepartmentService().findByName();
			if(list != null){
				com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
				for(Department dept :list){
					com.alibaba.fastjson.JSONObject json1 = (com.alibaba.fastjson.JSONObject) JSON.toJSON(dept);
					array.add(json1);
				}
				return array.toString();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return "false";
	}

}
